<template>
  <div class="key-value-editor">
    <div class="editor-header">
      <label class="checkbox-label">
        <input
          type="checkbox"
          v-model="allowPropertyEdit"
          @change="$emit('allow-edit-change', allowPropertyEdit)"
        />
        允许编辑属性名 （属性名称定义好以后，不要随意更改）
      </label>

      <!-- KeyValueEditor.vue 中 editor-header 部分的按钮 -->
      <div class="header-actions">
        <el-button type="primary" @click="addRootItem">添加根节点</el-button>
        <el-button type="secondary" @click="exportJson">导出JSON</el-button>
      </div>
    </div>

    <div class="editor-content">
      <div v-for="item in data" :key="item.id" class="root-item"> <!-- 使用id作为key -->
        <key-value-item
          :item="item"
          :level="0"
          :parent="{ value: data }"
          :is-editable="allowPropertyEdit"
          @update="() => {}"
          @remove="(itemId) => removeRootItem(itemId)"
          @add-child="addChild"
          @preview-video="handleVideoPreview"
          @preview-file="handleFilePreview"
        />
      </div>

      <div v-if="data.length === 0" class="empty-state">
        <p>暂无数据，点击"添加根键值对"开始编辑</p>
      </div>
    </div>

    <!-- JSON 输出区域 -->
    <div class="json-output-container">
      <h3>JSON 输出</h3>
      <div class="json-output">
        <pre>{{ formattedJson }}</pre>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      :visible.sync="dialogImageVisible"
      title="图片预览"
      width="80%"
      center
    >
      <img :src="dialogImageUrl" style="max-width: 100%; max-height: 70vh;" />
    </el-dialog>

    <!-- 视频播放组件 -->
    <video-column ref="videoColumn" />
  </div>
</template>

<script>
import KeyValueItem from '@/components/KeyValue/KeyValueItem.vue'
import VideoColumn from '@/components/VideoColumn/index.vue'
import { generateStableId } from '@/utils/idGenerator';
export default {
  name: 'KeyValueEditor',
  components: {
    KeyValueItem,
    VideoColumn
  },
  props: {
    jsonValue: {
      type: String,
      default: ''
    },
    allowEdit: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:modelValue', 'update:jsonValue', 'allow-edit-change'],
  data() {
    return {
      data: [],
      allowPropertyEdit: false,
      formattedJson: '{}',
      // 图片预览相关
      dialogImageVisible: false,
      dialogImageUrl: '',
      // 视频预览相关
      videoDialogVisible: false,
      currentVideoUrl: ''
    }
  },
  watch: {
    jsonValue: {
      handler(newVal) {
        if (newVal) {
          try {
            const parsedData = typeof newVal === 'string' ? JSON.parse(newVal) : newVal;
            const convertedData = this.convertFromJson(parsedData);
            // 将JSON字符串解析后的数据转换为内部数据结构
            this.data = this.processData(convertedData)
          } catch (error) {
            console.error('Invalid JSON string:', error)
            this.data = []
          }
        } else {
          console.log('jsonValue为空，设置空数组')
          this.data = []
        }
      },
      immediate: true
    },
    data: {
      handler(newVal) {
        // 将数据转换为JSON字符串并发出更新事件
        const jsonData = this.convertToJson(newVal)
        const jsonString = JSON.stringify(jsonData, null, 2);
        // this.$emit('update:jsonValue', JSON.stringify(jsonData, null, 2))
        this.updateFormattedJson()
        // this.$emit('update:jsonValue',this.formattedJson)
        this.$emit('update:jsonValue',jsonString)
      },
      deep: true
    },
    allowEdit: {
      handler(newVal) {
        this.allowPropertyEdit = newVal
      },
      immediate: true
    }
  },
  methods: {
    removeRootItem(itemId) {
      this.removeNodeById(this.data, itemId); // 复用递归删除方法
    },
    removeNodeById(list, targetId) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].id === targetId) {
          list.splice(i, 1);
          return true;
        }
        if (Array.isArray(list[i].value)) {
          const deleted = this.removeNodeById(list[i].value, targetId);
          if (deleted) return true;
        }
      }
      return false;
    },
    processData(data) {
      // 确保数据有id，同时保留展开状态
      return data.map(item => {
        const processedItem = {
        ...item,
         id: item.id || generateStableId()
      }

        // 如果是数组值，递归处理子项，同时保留展开状态
        if (Array.isArray(item.value)) {
          processedItem.value = this.processData(item.value)
        } else {
          processedItem.value = item.value
        }

        // 确保展开状态被保留，特别是对于有子项的节点
        if (Array.isArray(processedItem.value) && processedItem.value.length > 0 && processedItem.expanded === undefined) {
          processedItem.expanded = true
        }

        return processedItem
      })
    },

    // 获取当前数据
    getCurrentData() {
      return JSON.parse(JSON.stringify(this.data))
    },

    // 更新格式化的JSON
    updateFormattedJson() {
      try {
        const jsonData = this.convertToJson(this.data)
        this.formattedJson = JSON.stringify(jsonData, null, 2)
      } catch (error) {
        this.formattedJson = 'JSON格式错误: ' + error.message
      }
    },

    // 将编辑数据转换为标准JSON格式
    convertToJson(data) {
      const result = []
      data.forEach(item => {
        const itemObj = {
          remark: item.remark || '',
          [item.property]: item.value
        }
        // 如果是对象类型（数组值），递归转换
        if (Array.isArray(item.value)) {
          itemObj[item.property] = this.convertToJson(item.value)
        }
        result.push(itemObj)
      })
      return result
    },

    // 将JSON数据转换为内部编辑数据结构
    convertFromJson(jsonData) {
      if (!Array.isArray(jsonData)) {
        return []
      }

      return jsonData.map(item => {
        // 获取属性名（排除remark）
        const property = Object.keys(item).find(key => key !== 'remark') || ''
        const result = {
          property: property,
          remark: item.remark || '',
          type: 'text'
        }

        // 如果值是数组，递归转换
        if (Array.isArray(item[property])) {
          result.value = this.convertFromJson(item[property])
        } else {
          result.value = item[property] || ''
        }

        return result
      })
    },

    // 导出JSON
    exportJson() {
      const jsonData = this.convertToJson(this.data)
      const jsonStr = JSON.stringify(jsonData, null, 2)

      // 创建下载链接
      const blob = new Blob([jsonStr], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'key-value-data.json'
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    },

    // 添加根键值对
    addRootItem() {
      const newItem = {
        id: generateStableId(), // 生成唯一id
        property: '',
        remark: '',
        value: '',
        type: 'text'
      }
      this.data.push(newItem)
    },

    removeItem(index) {
      // 直接根据索引移除根级项目
      if (typeof index === 'number' && index >= 0 && index < this.data.length) {
        this.data.splice(index, 1)
      }
    },

    addChild(parentItem) {
      // 此方法已在子组件中处理了添加逻辑，这里只需触发更新事件确保数据同步
      this.$emit('update:modelValue', this.getCurrentData())
    },

    // 处理视频预览
    handleVideoPreview(videoUrl) {
      this.currentVideoUrl = videoUrl;
      this.$refs.videoColumn.openVideo(videoUrl);
    },

    // 处理文件预览
    handleFilePreview(fileUrl) {
      // 判断是否为图片URL
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
      const isImage = imageExtensions.some(ext => fileUrl.toLowerCase().includes(ext));

      if (isImage) {
        // 图片预览
        this.dialogImageUrl = fileUrl;
        this.dialogImageVisible = true;
      } else {
        // 其他文件类型可以在此处扩展处理逻辑
        // 目前简单地在新标签页打开
        window.open(fileUrl, '_blank');
      }
    },

    // 加载外部数据
    loadData(newData) {
      this.data = this.processData(newData)
    },

    // 清空数据
    clearData() {
      this.data = []
    }
  }
}
</script>

<style scoped>
.key-value-editor {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  width: 100%;
  margin: 0;
  padding: 0;
  text-align: left;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  border-radius: 8px 8px 0 0;
  flex-wrap: wrap;
  gap: 12px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #495057;
  cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
  margin: 0;
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.editor-content {
  padding: 8px 0 16px 4px;
  background: white;
  border: 1px solid #e5e7eb;
  border-top: none;
  border-radius: 0 0 0.375rem 0.375rem;
}

.root-item {
  margin-bottom: 2px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

/* JSON 输出区域样式 */
.json-output-container {
  margin-top: 16px;
  background: #f8f9fa;
  border: 1px solid #e5e7eb;
  border-radius: 0.375rem;
  padding: 16px;
}

.json-output-container h3 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 16px;
  color: #334155;
  font-weight: 600;
}

.json-output {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 0.25rem;
  padding: 12px;
  max-height: 200px;
  overflow: auto;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
}

.json-output pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

@media (max-width: 768px) {
  .editor-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }
}
</style>
